package concurrecy;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class PriorityThread implements Runnable {
    private volatile double d;
    private int priority;
    private int countDown = 5;
    public PriorityThread(int priority) {
        this.priority = priority;
    }

    @Override
    public String toString() {
        return Thread.currentThread() + ": " + countDown;
    }

    @Override
    public void run() {
        Thread.currentThread().setPriority(priority);
        Random random = new Random();
        while(true) {
            for (int i = 0; i < 100000; i++) {
                d *= (Math.PI + Math.E) / random.nextDouble();
                if (i % 1000 == 0) {
                    Thread.yield();
                }
            }
            if (countDown-- < 0)
                return;
            System.out.println(this);
        }
    }
}

public class PriorityDemo {
    public static void main(String[] args) {
        System.out.println(Runtime.getRuntime().availableProcessors());
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < 16; i++) {
            service.execute(new PriorityThread(Thread.MIN_PRIORITY));
        }
        service.execute(new PriorityThread(Thread.MAX_PRIORITY));
        service.shutdown();
    }
}
